package com.neusoft.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.neusoft.mapper.*;
import com.neusoft.po.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.neusoft.service.OrdersService;
import com.neusoft.util.CommonUtil;

@Service
public class OrdersServiceImpl implements OrdersService {

	@Autowired
	private CartMapper cartMapper;

	@Autowired
	private OrdersMapper ordersMapper;

	@Autowired
	private OrderDetailetMapper orderDetailetMapper;

	@Autowired
	private PointMapper pointMapper;

	@Autowired
	private CouponMapper couponMapper;


	@Override
	@Transactional
	public int createOrders(Orders orders) {
		// 1.查询当前用户购物车中当前商家的所有食品
		Cart cart = new Cart();
		cart.setBusinessId(orders.getBusinessId());
		cart.setUserId(orders.getUserId());
		int num = cartMapper.checkCart(cart);
		if(num == 0) {//购物车中没有物品，返回0，表示增加失败
			return 0;
		}
		List<Cart> cartlist = cartMapper.listCart(cart);

		// 2.创建订单（向订单表中插入数据，并返回订单编号，用于插入订单明细）
		orders.setOrderDate(CommonUtil.getCurrentDate());
		ordersMapper.saveOrders(orders); // 这里是返回的行数，并不是我们关心的订单编号
		int orderId = orders.getOrderId();

		// 3.批量添加订单明细
		List<OrderDetailet> list = new ArrayList<>();
		for (Cart c : cartlist) {
			OrderDetailet od = new OrderDetailet();
			od.setOrderId(orderId);
			od.setFoodId(c.getFoodId());
			od.setQuantity(c.getQuantity());
			list.add(od);
		}
		orderDetailetMapper.saveOrderDetailetBatch(list);
		// 4.从购物车表中删除相关食品信息
		cartMapper.removeCart(cart);

		//对coupon和point进行扣取
		try {
			String couponName = orders.getCoupon();
			Coupon coupon = couponMapper.getCouponById(orders.getUserId());
			switch (couponName) {
				case "coupon_10_2":
					if(coupon.getCoupon_10_2()==0){
						throw new IllegalArgumentException("Invalid input parameter");
					}
					coupon.setCoupon_10_2(coupon.getCoupon_10_2() - 1);
					break;
				case "coupon_20_3":
					if(coupon.getCoupon_20_3()==0){
						throw new IllegalArgumentException("Invalid input parameter");
					}
					coupon.setCoupon_20_3(coupon.getCoupon_20_3() - 1);
					break;
				case "coupon_30_5":
					if(coupon.getCoupon_30_5()==0){
						throw new IllegalArgumentException("Invalid input parameter");
					}
					coupon.setCoupon_30_5(coupon.getCoupon_30_5() - 1);
					break;
				case "coupon_20_6":
					if(coupon.getCoupon_20_6()==0){
						throw new IllegalArgumentException("Invalid input parameter");
					}
					coupon.setCoupon_20_6(coupon.getCoupon_20_6() - 1);
					break;
				case "coupon_30_10":
					if(coupon.getCoupon_30_10()==0){
						throw new IllegalArgumentException("Invalid input parameter");
					}
					coupon.setCoupon_30_10(coupon.getCoupon_30_10() - 1);
					break;
				case "coupon_50_15":
					if(coupon.getCoupon_50_15()==0){
						throw new IllegalArgumentException("Invalid input parameter");
					}
					coupon.setCoupon_50_15(coupon.getCoupon_50_15() - 1);
					break;
				default:
					// 如果couponName不是六种劵名中的任何一个，不执行任何操作
					break;
			}
			// 更新coupon表中的数据
			couponMapper.updateCouponbyId(coupon);

			// 根据使用积分来对积分进行扣取
			int pointLoss = orders.getPoints();
			if (pointLoss != 0) {
				List<Point> points = pointMapper.getPoints(orders.getUserId());
				Iterator<Point> iterator = points.iterator();
				while (iterator.hasNext() && pointLoss != 0) {
					Point point = iterator.next();
					if (pointLoss >= point.getPoints()) {//如果超了就删除
						pointLoss -= point.getPoints();
						pointMapper.deletePoints(point);
					} else {//否则修改该积分信息
						point.setPoints(point.getPoints()-pointLoss);
						pointLoss = 0;
						pointMapper.updatePoint(point);
					}
				}
				if(pointLoss!=0) {
					throw new IllegalArgumentException("Invalid input parameter");
				}
			}
		}catch (Exception e) {
			throw new RuntimeException("Failed to create orders", e);
		}
		return orderId;// 前端只是用来判断是否成功
	}

	@Override
	public Orders getOrdersById(Integer orderId) {
		return ordersMapper.getOrdersById(orderId);
	}

	@Override
	public List<Orders> listOrdersByUserId(String userId) {
		return ordersMapper.listOrdersByUserId(userId);
	}

	@Override
	@Transactional
	public int finishOrders(Orders orders) {

		orders = ordersMapper.getOrdersById(orders.getOrderId());
		if(orders == null) {
			return 0;//订单不存在
		}
		if(orders.getOrderState()==1) {
			return 0;//或者已经支付
		}
		ordersMapper.finishOrders(orders);
		// 创建Point对象，对其进行调用
		Point point = new Point();
		double orderTotal = orders.getOrderTotal();
		int points = (int) Math.floor(orderTotal);
		point.setPoints(points);
		point.setPurchaseDate(CommonUtil.getCurrentDate());
		point.setUserId(orders.getUserId());
		pointMapper.savePoints(point);

		return 1;
	}

	@Override
	@Transactional
	public List<Orders> deleteOrders(Orders orders) {
		orders = ordersMapper.getOrdersById(orders.getOrderId());
		if(orders == null || orders.getOrderState() == 1)
			return null;
		//对于优惠券进行返还
		if(orders.getCoupon()!= null){
			Coupon c = new Coupon();
			c.setUserId(orders.getUserId());
			String coupon = orders.getCoupon();
			if(coupon.equals("coupon_10_2")){
				c.setCoupon_10_2(1);
			}else {
				c.setCoupon_10_2(0);
			}
			if(coupon.equals("coupon_20_3")) {
				c.setCoupon_20_3(1);
			}else {
				c.setCoupon_20_3(0);
			}
			if(coupon.equals("coupon_30_5")){
				c.setCoupon_30_5(1);
			}else {
				c.setCoupon_30_5(0);
			}
			if(coupon.equals("coupon_20_6")){
				c.setCoupon_20_6(1);
			}else {
				c.setCoupon_20_6(0);
			}
			if(coupon.equals("coupon_30_10")) {
				c.setCoupon_30_10(1);
			}else {
				c.setCoupon_30_10(0);
			}
			if(coupon.equals("coupon_50_15")) {
				c.setCoupon_50_15(1);
			}else {
				c.setCoupon_50_15(0);
			}

			couponMapper.returnCoupon(c);
		}


		//对于积分进行更新,返回60%积分
		int p = orders.getPoints();
		if(p!=0) {
			int points=(int) (p*0.6);
			Point point = new Point();
			point.setPoints(points);
			point.setUserId(orders.getUserId());
			point.setPurchaseDate(CommonUtil.getCurrentDate());
			pointMapper.savePoints(point);
		}
		//订单明细表删除
		orderDetailetMapper.deleteOrderDetailet(orders.getOrderId());
		//从订单表里面删除该订单
		ordersMapper.deleteOrders(orders);
		//返回删除后的订单
		return ordersMapper.listOrdersByUserId(orders.getUserId());
	}
}